<template>
  <div class="menu">
    <el-tabs v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane :label="translateTitle('Dams.ApplicationInterface.DAMS菜单')" name="first">
        <div class="common-head flex">
          <el-button type="primary" @click="addMenu">{{ translateTitle('Dams.ApplicationInterface.新增') }}</el-button>
          <el-button v-if="activeName == 'first'" type="primary" @click="exportMenu">
            {{ translateTitle('Dams.ApplicationInterface.导出') }}
          </el-button>
          <vui-upload
            v-if="activeName == 'first'"
            ref="fileUploadRef"
            :auto-upload="true"
            :file-name="uploadOptions.name"
            :limit="1"
            :post-data="uploadOptions.postData"
            :show-file-list="false"
            style="margin-left: 12px"
            :url="uploadOptions.url"
            @uploadSuccess="uploadSuccess"
          >
            <el-button type="primary">{{ translateTitle('Dams.ApplicationInterface.导入') }}</el-button>
          </vui-upload>
        </div>
        <vxe-table
          :ref="`xTree_${subSystem}`"
          align="center"
          border
          :checkbox-config="tableCheckboxConfig"
          :column-config="{ resizable: true }"
          :data="treeData"
          :height="`${getHeight - 115}`"
          highlight-current-row
          highlight-hover-row
          :tree-config="tableTreeConfig"
        >
          <vxe-column field="MENU_NAME" :title="translateTitle('Dams.ApplicationInterface.菜单名称')" tree-node type="checkbox" />
          <vxe-column field="LANGUAGE_CODE" :title="translateTitle('Dams.ApplicationInterface.语言类型')" />
          <vxe-column field="MENU_URL" :title="translateTitle('Dams.ApplicationInterface.菜单地址')" />
          <vxe-column :title="translateTitle('Dams.ApplicationInterface.操作')" width="300">
            <template #default="{ row }">
              <vxe-button type="text" @click="editorMenu(row)">{{ translateTitle('Dams.ApplicationInterface.编辑') }}</vxe-button>
              <vxe-button v-if="row.PID || (!row.PID && row.children.length == 0)" type="text" @click="deleteMenu(row)">
                {{ translateTitle('Dams.ApplicationInterface.删除') }}
              </vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-model="addDialog"
      :close-on-click-modal="false"
      :title="translateTitle('Dams.ApplicationInterface.菜单增改')"
      width="60%"
      @close="close"
    >
      <el-form ref="formDialog" label-width="90px" :model="formDialog" :rules="rules">
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单名称')" prop="MENU_NAME" style="margin-bottom: 22px">
          <!-- <el-input v-model="formDialog.MENU_NAME" /> -->
          <el-select
            v-model="formDialog.MENU_NAME"
            filterable
            :placeholder="translateTitle('Dams.ApplicationInterface.请选择')"
            remote
            :remote-method="remoteMethod"
          >
            <el-option v-for="item in menuNameOptions" :key="item.CODE_ID" :label="item.NAME" :value="item.CODE_ID" />
          </el-select>
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.上级菜单')" prop="MENU_CODE" style="margin-bottom: 22px">
          <el-cascader
            ref="myCascader"
            v-model="formDialog.MENU_CODE"
            clearable
            :disabled="type == 'editor'"
            :options="options"
            :props="{ checkStrictly: true, value: 'value', label: 'label', emitPath: false }"
            :show-all-levels="false"
            @change="cascaderChange"
          />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.语言类型')" prop="LANGUAGE_CODE" style="margin-bottom: 22px">
          <!-- <el-input v-model="formDialog.LANGUGE_CODE" /> -->
          <el-select v-model="formDialog.LANGUAGE_CODE" disabled :placeholder="translateTitle('Dams.ApplicationInterface.请选择')">
            <el-option v-for="item in languageOptions" :key="item.LANGUAGE_CODE" :label="item.LANGUAGE_DESC" :value="item.LANGUAGE_CODE" />
          </el-select>
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单地址')" style="margin-bottom: 22px">
          <el-input v-model="formDialog.MENU_URL" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单ICON')" style="margin-bottom: 22px">
          <exIcon :info="info" />
        </el-form-item>
        <el-form-item :label="translateTitle('Dams.ApplicationInterface.菜单排序')" style="margin-bottom: 22px">
          <el-input-number v-model="formDialog.SORT" :label="translateTitle('Dams.ApplicationInterface.描述文字')" :max="999" :min="1" />
        </el-form-item>
        <el-form-item style="margin-bottom: 22px">
          <el-button type="primary" @click="onSubmit('formDialog')">{{ translateTitle('Dams.ApplicationInterface.确定') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import { Mixin } from '@/common/minxin/Mixin'
  import exIcon from '@ve/layout/extension/components/exIcon.vue'
  import { GFCD } from '@/utils/utils'
  import { getList, download } from '../api/home'
  import debounce from 'lodash/debounce'
  import { componentId } from '@/utils/unique'
  import cloneDeep from 'lodash/cloneDeep'
  import { translateTitle } from '@/utils/i18n'
  export default {
    name: 'PublicMenu',
    components: { exIcon },
    mixins: [Mixin],
    props: {
      //所属子系统
      subSystem: {
        type: String,
        default: '',
      },
      //接口对象
      portObj: {
        type: Object,
        default: () => {},
      },
      //父组件name
      name: {
        type: String,
        default: '',
      },
      btnFix: {
        type: Boolean,
        default: false,
      },
    },
    data() {
      return {
        copyLoading: false,
        languageOptions: [],
        copyMenu: [],
        copyOptions: [],
        menuNameOptions: [],
        copyDialog: false,
        info: {
          type: 'exIcon',
          name: 'name',
          value: '',
        },
        rules: {
          MODEL_ID: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入模块ID'), trigger: 'blur' }],
          MENU_NAME: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择菜单名称'), trigger: 'blur' }],
          MENU_CODE: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择上级'), trigger: 'change' }],
          LANGUAGE_CODE: [{ required: true, message: translateTitle('Dams.ApplicationInterface.请选择语言类型'), trigger: 'blur' }],
        },
        options: [
          {
            value: 'top',
            label: translateTitle('Dams.ApplicationInterface.顶级菜单'),
            children: [],
          },
        ],
        editorItem: {},
        tableTreeConfig: {
          transform: true,
          rowField: 'ID',
          parentField: 'PID',
        },
        activeName: 'first',
        treeData: [],
        addDialog: false,
        formDialog: { SORT: 1 },
        level: 1,
        type: 'add',
        clientHeight: 0,
        configSetting: {},
        unilineData: {},
        uploadOptions: {},
      }
    },
    computed: {
      getHeight() {
        return `${this.clientHeight - 100}`
      },
      tableCheckboxConfig() {
        return {
          labelField: 'MENU_NAME',
          // checkMethod: ({ row }) => {
          //   return row.ID != '100' && row.PID != '100'
          // },
          visibleMethod({ row }) {
            if (row.PID) {
              return row.JUMP == 'Y'
            } else {
              let ids = ['100', 'lpms100', 'lwms100', 'les100', 'wcs100']
              return ids.indexOf(row.ID) == -1
            }
          },
        }
      },
    },
    created() {
      if (this.subSystem == 'DAMS') {
        delete this.rules.MODEL_ID
      } else {
        this.rules.MODEL_ID = [{ required: true, message: translateTitle('Dams.ApplicationInterface.请输入模块ID'), trigger: 'blur' }]
      }
      let url = GFCD('dams')
      this.uploadOptions = {
        postData: {
          method: 'dams.page.import',
          data: JSON.stringify({ SYS_CODE: this.subSystem }),
        },
        name: 'uploadFile',
        url: `${url.domain}${url.baseUrl}`,
      }
      this.init()
    },
    methods: {
      async remoteMethod(query) {
        if (query !== '') {
          let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
            data: JSON.stringify({
              '#LIMIT#': 1,
              '#PAGE_SIZE#': 99999,
              SUB_SYSTEM: 'DAMS',
              name: query,
            }),
            method: 'dams.language.pack.select.query',
          })
          this.menuNameOptions = res.data['dams.language.pack.select.query'].data
        } else {
          this.menuNameOptions = []
        }
      },
      translateTitle,
      async exportMenu() {
        if (this.$refs[`xTree_${this.subSystem}`].getCheckboxRecords().length == 0)
          return this.$baseMessage(translateTitle('Dams.ApplicationInterface.请选择菜单'), 'error')
        let arr = this.$refs[`xTree_${this.subSystem}`].getCheckboxRecords().filter((el) => el.PID)
        let list = []
        arr.forEach((row) => {
          list.push({ MENU_CODE: row.ID })
        })
        let url = GFCD('dams')
        let res = await download(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ SYS_CODE: this.subSystem, MENU: list }),
          method: 'dams.page.export',
        })
        let blob = new Blob([res], { type: 'text/xml' })
        let reader = new FileReader()
        reader.readAsDataURL(blob) // 转换为base64，可以直接放入a标签href
        reader.onload = (e) => {
          let a = document.createElement('a')
          a.download = translateTitle('Dams.ApplicationInterface.导出文件') + '_' + new Date().getTime() + '.txt'
          a.href = e.target.result
          a.click()
        }
      },
      getBracketData(str) {
        if (str.indexOf('{') != -1 && str.indexOf('}') != -1) {
          let a1 = /\{(.+?)\}/g //正则获取小括号
          let a2 = str.match(a1).toString() //因为输出的是数组，所以得转化成字符串
          var a3 = a2.replace('{', '') //用空字符替换掉括号
          a3 = a3.replace('}', '')
          console.log(a3) //最终得到括号里面的数字
          return a3
        }
      },
      uploadSuccess(file) {
        let res = file.fileList[0].response
        this.$message({
          type: this.getBracketData(res.msg),
          message: res.msg,
        })
        this.getWmsTree()
      },
      async getLanguage() {
        let url = GFCD('dams')
        let res = await getList(`${url.domain}${url.baseUrl}`, {
          data: JSON.stringify({ '#LIMIT#': 1, '#PAGE_SIZE#': 9999 }),
          method: 'dams.language.query',
        })
        this.languageOptions = res.data['dams.language.query'].data
        // console.log(res.data['dams.language.query'].data)
      },
      editorMenu(row) {
        console.log(row)
        this.menuNameOptions = [{ CODE_ID: row['MENU_NAME_CODE'], NAME: row['MENU_NAME'] }]
        this.editorItem = row
        this.type = 'editor'
        this.info.value = row.MENU_ICON
        this.formDialog.MENU_ICON = row.MENU_ICON
        this.formDialog.MODEL_ID = row.MODEL_ID
        this.formDialog.MENU_CODE = row.PID ? row.PID : 'top'
        // this.formDialog.MENU_NAME = row.MENU_NAME
        this.formDialog.MENU_NAME = row.MENU_NAME_CODE
        this.formDialog.SUB_SYSTEM = this.subSystem
        this.formDialog.LANGUAGE_CODE = row.LANGUAGE_CODE
        this.formDialog.SORT = row.SORT ? row.SORT : 1
        if (row.PID) {
          //第二级
          this.formDialog.MENU_URL = row.MENU_URL
          this.level = 2
          this.formDialog.MENU_SCODE = this.formDialog.MENU_CODE
          this.formDialog.MENU_LV = '2'
          this.formDialog.id = row.ID
        } else {
          //第一级
          this.formDialog.MENU_LV = '1'
          this.level = 1
          this.formDialog.id = row.ID
        }
        this.addDialog = true
      },
      deleteMenu(row) {
        this.$confirm(translateTitle('Dams.ApplicationInterface.确定删除'), translateTitle('Dams.ApplicationInterface.提示'), {
          confirmButtonText: translateTitle('Dams.ApplicationInterface.确定'),
          cancelButtonText: translateTitle('Dams.ApplicationInterface.取消'),
          type: 'warning',
        })
          .then(async () => {
            let url = `${this.configSetting.domain}${this.configSetting.baseUrl}`
            let method, obj
            method = this.portObj.dele
            obj = { MENU_CODE: row.ID }
            await getList(url, {
              data: JSON.stringify(obj),
              method: method,
            })
            this.$message({
              type: 'success',
              message: translateTitle('Dams.ApplicationInterface.删除成功') + `!`,
            })
            this.getWmsTree()
          })
          .catch((e) => {
            console.log(e)
          })
      },
      onSubmit(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.formDialog.SUB_SYSTEM = this.subSystem
            this.formDialog.MENU_ICON = this.info.value
            if (this.formDialog.MENU_CODE == 'top') {
              this.formDialog.MENU_LV = '1'
              this.level = 1
            } else {
              this.formDialog.MENU_URL = this.formDialog.MENU_URL ? this.formDialog.MENU_URL : `page_${componentId(6)}`
              this.level = 2
              this.formDialog.MENU_SCODE = this.formDialog.MENU_CODE
              this.formDialog.MENU_LV = '2'
            }
            this.setData()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      async setData() {
        console.log(this.type)
        let method = ''
        let obj = {}
        if (this.activeName == 'first') {
          if (this.type == 'add') {
            if (this.level == 1) {
              method = this.portObj.firstAdd
            } else {
              method = this.portObj.secondAdd
            }
            obj = { ...this.formDialog }
          } else {
            if (this.level == 1) {
              method = this.portObj.firstEdit
            } else {
              method = this.portObj.secondEdit
            }
            obj = { ...this.formDialog }
          }
          obj.MENU_CODE = obj.id
          delete obj.id
        }
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(obj),
          method: method,
        })
        console.log(res)
        this.addDialog = false
        this.formDialog = { SORT: 1 }
        this.$message({
          type: 'success',
          message: translateTitle('Dams.ApplicationInterface.修改成功') + `!`,
        })
        this.getWmsTree()
      },
      cascaderChange() {
        console.log(this.$refs['myCascader'].getCheckedNodes()[0])
        this.editorItem = this.$refs['myCascader'].getCheckedNodes()[0].data
      },
      handleClick() {},
      windowResize: debounce(function () {
        console.log('document.documentElement.clientHeight', document.documentElement.clientHeight)
        this.clientHeight = document.documentElement.clientHeight
      }, 100),
      close() {
        this.addDialog = false
        this.formDialog = { SORT: 1 }
      },
      addMenu() {
        this.type = 'add'
        this.addDialog = true
        this.formDialog.LANGUAGE_CODE = this.$store.getters['user/language']
        this.formDialog.SORT = 1
      },
      getWmsTree() {
        this.getTree()
      },
      async getTree() {
        let p = {}
        let method
        p = { SUB_SYSTEM: this.subSystem, '#LIMIT#': 1, ATTRIBUTION_CODE: 'PC', '#PAGE_SIZE#': 9999 }
        method = this.portObj.query
        p.LANGUAGE_CODE = this.$store.getters['user/language']
        let res = await getList(`${this.configSetting.domain}${this.configSetting.baseUrl}`, {
          data: JSON.stringify(p),
          method: method,
        })
        let firstData = cloneDeep(res.data.first.data)
        firstData.forEach((row) => {
          row.MENU_URL = ''
        })
        let arr = firstData.concat(res.data.second.data)
        res.data.first.data.forEach((row) => {
          row.label = row.MENU_NAME
          row.value = row.ID
          row.children = []
          res.data.second.data.forEach((item) => {
            if (item.PID === row.ID) {
              row.children.push({
                PID: item.PID,
                value: item.ID,
                label: item.MENU_NAME,
                disabled: true,
              })
            }
          })
        })
        this.options[0].children = res.data.first.data
        this.treeData = arr
      },
      init() {
        this.configSetting = GFCD(this.subSystem.toLocaleLowerCase())
        this.windowResize()
        this.getLanguage()
        this.getWmsTree()
      },
    },
  }
</script>

<style lang="scss">
  @import '@/ve/elements/basic/uiTable/style.scss';
  @import '@/ve/styles/elements.scss';
  .menu {
    padding: 10px;
    overflow-y: auto;
    // display: flex;
    background: #ebeef5;
    .common-head {
      padding: 14px 10px;
    }
    :deep() {
      .vxe-icon--caret-right:before {
        border-top-color: transparent;
        border-right-color: transparent;
        border-bottom-color: transparent;
        border-left-color: #000;
      }
      .el-tabs--border-card > .el-tabs__content {
        padding: 0;
      }
    }
  }
</style>
